package com.starbaba.system.user.dao;

import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;

import com.starbaba.core.hibernate.DAOFactory;
import com.starbaba.core.hibernate.HibernateDAO;
import com.starbaba.core.hibernate.Strategy;
import com.starbaba.core.web.constant.WebConstants;
import com.starbaba.core.web.sequence.Sequence;
import com.starbaba.system.user.model.UserLogVO;
import com.starbaba.system.user.model.UserVO;

@SuppressWarnings("serial")
public class UserStrategy implements Strategy {
	
	private UserVO curVO;
	
	private UserVO userVO;
	
	private String oprType = WebConstants.OPRTYPE_ADD;

	public UserStrategy(UserVO curVO, UserVO userVO) {
		this.curVO = curVO;
		this.userVO = userVO;
	}

	@Override
	public Object process() throws Exception {
		HibernateDAO urerDAO = DAOFactory.getInstance().createHibernateDAO(UserVO.class);
		HibernateDAO urerLogDAO = DAOFactory.getInstance().createHibernateDAO(UserLogVO.class);
		
		UserLogVO logVO = new UserLogVO();
		BeanUtils.copyProperties(logVO, curVO);
		logVO.setLogId(Sequence.getSequence());
		logVO.setOprCode(userVO.getUserid());
		logVO.setOprTime(new Date());
		logVO.setOprType(oprType);
		urerLogDAO.save(logVO);
		
		if(WebConstants.OPRTYPE_ADD.equals(oprType)){
			List<?> list = urerDAO.findByHQL(" from UserVO where userId = ? ", new Object[]{curVO.getUserid()});
			if(null != list && list.size()> 0){
				throw new Exception("用户已经存在");
			}
			urerDAO.save(curVO);
		}else if(WebConstants.OPRTYPE_MODIFY.equals(oprType)){
			UserVO thisVO = (UserVO) urerDAO.findByPK(curVO.getUserid());
			if(null == thisVO){
				urerDAO.saveOrUpdate(curVO);
			}else{
//				thisVO.setStatus(curVO.getStatus());
//				//thisVO.setUserType(curVO.getUserType());
//				thisVO.setUserName(curVO.getUserName());
//				thisVO.setMobileno(curVO.getMobileno());
//				thisVO.setEmail(curVO.getEmail());
				BeanUtils.copyProperties(thisVO, curVO);
				urerDAO.saveOrUpdate(thisVO);
			}
		}else{
			throw new Exception("操作标识错误");
		}
		return null;
	}

	public UserVO getCurVO() {
		return curVO;
	}

	public void setCurVO(UserVO curVO) {
		this.curVO = curVO;
	}

	public UserVO getUserVO() {
		return userVO;
	}

	public void setUserVO(UserVO userVO) {
		this.userVO = userVO;
	}

	public String getOprType() {
		return oprType;
	}

	public void setOprType(String oprType) {
		this.oprType = oprType;
	}

}
